(function(){
    /**
	 * @class Bible.BibleGridPanel
	 * @extends Ext.grid.EditorGridPanel
	 */
	var separator = '.',
        BOOKS_URL = 'servlets/books.php',
        CHAPTERS_URL = 'servlets/chapters.php',
        VERSE_URL = 'servlets/verse.php',

        START_REF_REG_EXP = new RegExp(Ext.escapeRe('#'), 'g'),
        END_REF_REG_EXP = new RegExp(Ext.escapeRe('$'), 'g'),

    BibleGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
		cls: 'bible-grid',
		hideHeaders: true,
		columnLines: true,
        autoExpandColumn: 'text',
        clicksToEdit: 1,

        /**
         * @cfg {Boolean} autoLoad true to autoLoad store. defaults to true
         */
        autoLoadChapter: true,

		initComponent: function(){
            var me = this,
                hashBook,
                actions = Bible.getActions();
            if(me.hashBook && (hashBook = actions[me.hashBook])){
                var defaultActions = hashBook.split(separator);
                me.defaultBook = Ext.num(parseInt(defaultActions[0]), 1);
                me.defaultChapter = Ext.num(parseInt(defaultActions[1]), 1);
                me.defaultVerse = defaultActions[2]; // TODO make this public
            } else {
                me.defaultBook = 1;
                me.defaultChapter = 1;
            }

			me.chaptersStore = new Ext.data.ArrayStore({
				fields: ['id'],
				data : [[1]]
			});

			// create the data store
            me.store = new Ext.data.ArrayStore({
				showBackgroundColors: true,

                proxy: new Ext.data.HttpProxy(new Ext.data.Connection({
                    method: 'GET',
                    url: CHAPTERS_URL,
					autoAbort: true
				})),
				idIndex: 0,
                root: 'data',
                baseParams: {
					action: 'get_chapter',
					references: Bible.defaults.references,
					titles: Bible.defaults.titles
				},
                fields: [
                    {name: 'id', type: 'int'},
                    {name: 'cnumber', type: 'int'},
                    {name: 'vnumber', type: 'int'},
                    {name: 'text', type: 'string'},
                    {name: 'title', type: 'string'},
                    {name: 'ref', type: 'string'},
                    // user specific changes
                    {name: 'comment', type: 'string'},
                    {name: 'bgcolor', type: 'string'},
                    {name: 'keyverse', type: 'string'}
                ]
			});

			me.checkFilter = new Ext.Button({
                iconCls: 'icon-filter',
				tooltip: i18n.filter,
				enableToggle: true
			});

			// TODO must create termshighlight class only not search
			me.searchField = new Bible.form.SearchFieldLocal({
                emptyText: 'Evidenţiază cuvinte...', // TODO i18n
                trigger2Qtip: 'Caută/Evidenţiază cuvinte în capitolul curent',
				store: me.store,
				filterByFields: ['text'],
                checkFilter: me.checkFilter,
				split: true,
                width: 145
			});
			me.store.searchField = me.searchField;

            me.commentEditor = new Ext.form.TextArea({
				cls: 'comment-editor',
                style: 'padding: 3px 6px',
                //grow: true, // TODO try to implement but ho have boxMinHeight min 60 or row height
                boxMinHeight: 62
            });

            var commentEditor2 = new Ext.grid.GridEditor(me.commentEditor, {
                offsets: [-2, -1]
            });

            var columns = [
                new Ext.grid.RowNumberer({
                    width: 27,
                    dataIndex: 'vnumber',
                    renderer : function(v, p, record){
                        if(this.rowspan){
                            p.cellAttr = 'rowspan="'+this.rowspan+'"';
                        }
                        var title = record.get('title');
                        if(title){
                            v = '<b ext:qtip="'+title+'">'+ v +'</b>';
                        }

                        if(record.get('keyverse')){
                            p.css = 'gold-verse';
                        }
                        return v;
                    }
                }),
                {
                    id:'text',
                    dataIndex: 'text',
                    width: 75,
                    renderer: function(val, metaData, record, rowIndex, colIndex, store){
                        var title,
                            ref,
							highlightText = Bible.highlightTerms(val, store);
                        me.keywordsMatches = me.keywordsMatches.concat(highlightText.matches);
                        if(store.showKeywords){
							val = highlightText.text;
						}
//                        val = '<span class="verse-nr">('+record.get('vnumber')+')</span> ' + val;

                        if(store.baseParams.titles){
                            title = record.get('title');
                            if(title){
                                val = '<div class="title">' +title+ '</div>' + val;
                            }
                        }
                        if(store.baseParams.references){
                            ref = record.get('ref');
                            if(ref){
                                ref = ref.replace(START_REF_REG_EXP,
                                        '<span class="ref" ext:qwidth="200" ext:qtip=" " ext:qurl="' + VERSE_URL + '?id=');
                                ref = ref.replace(END_REF_REG_EXP, '</span>');
                                val += '<div class="references">' +ref+ '</div>';
                            }
                        }
                        if(store.showBackgroundColors && record.get('bgcolor')){
                            metaData.attr = 'style="background-color: #'+ record.get('bgcolor') +';"';
                        }
                        return val;
                    }
                },
                {
                    id:'comments',
                    dataIndex: 'comment',
                    width: 200,
                    fixed: true,
                    hidden: true,
                    renderer: Bible.rendererComments,
                    editor: commentEditor2
                },
                {
                    id: 'comments-img',
                    dataIndex: 'comment',
                    width: 27,
                    fixed: true,
                    hideable: false,
                    menuDisabled: true,
                    renderer: function(v, metaData){
                        if(v){
                            metaData.css = 'comment-knotes';
                        }
                        return '';
                    }
                }
            ];


			Ext.apply(me, {
                keywordsMatches: [],
				viewConfig: {
                    autoFill: true,
					forceFit: true,
//					scrollOffset: 1,
                    templates: {
                        cell: new Ext.XTemplate(
                            '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>',
                                '<div class="x-grid3-cell-inner x-grid3-col-{id}" <tpl if="id != \'text\'">unselectable="on"</tpl> {attr}>{value}</div>',
                            '</td>'
                        )
                    }
				},
                keys: [
                    {
                        key: Ext.EventObject.RIGHT,
                        ctrl:true,
                        fn: function() {
                            console.debug('Ctrl+RIGHT moveNext');
                            me.getBottomToolbar().moveNext();
                        }
                    },
                    {
                        key: Ext.EventObject.LEFT,
                        ctrl:true,
                        fn: function() {
                            console.debug('Ctrl+LEFT movePrevious');
                            me.getBottomToolbar().movePrevious();
                        }
                    },
                    {
                        key: Ext.EventObject.PAGE_DOWN,
                        fn: function() {
                            var view = me.view,
                                scroller = view.scroller;
                            console.debug('PAGE_DOWN');
//                            console.debug('scrollTop, scroller, mainBody',
//                                    scroller.dom.scrollTop, scroller.getHeight(), view.mainBody.getHeight());
//                            console.info( 'TOTAL    :', view.mainBody.getHeight() - scroller.getHeight());
                            if((view.mainBody.getHeight() - scroller.getHeight() - scroller.dom.scrollTop) <= 0){
                                console.info('PAGE_DOWN moveNext');
                                me.getBottomToolbar().moveNext();
                            }
                        }
                    },
                    {
                        key: Ext.EventObject.PAGE_UP,
                        fn: function() {
                            var view = me.view,
                                scroller = view.scroller;
                            console.debug('PAGE_UP');
                            if(scroller.dom.scrollTop == 0){
                                console.info('PAGE_UP movePrevious');
                                me.getBottomToolbar().movePrevious();
                            }
                        }
                    },
                    {
                        key: Ext.EventObject.C,
                        shift:true,
                        fn: function(){
                            console.debug('Shift + C');
                            me.commentsButton.toggle();
                        }
                    },
					{
                        key: Ext.EventObject.K,
                        shift:true,
                        fn: function(){
                            console.debug('Shift + K');
                            me.keywordsButton.toggle();
                        }
                    },
					{
                        key: Ext.EventObject.R,
                        shift:true,
                        fn: function(){
                            console.debug('Shift + R');
                            me.referencesButton.toggle();
                        }
                    },
                ],
				sm: new Ext.grid.RowSelectionModel({
					singleSelect: true
				}),
				tbar: new Ext.Container({
                    items: [
                        new Ext.Toolbar({
                            enableOverflow: true, // TODO items are not shown all
                            items: (function(){
								var items = me.getTopToolbarItems();
								items.push(me.getSecondTopToolbarItems());
								return items;
							})()
                        }),
                        me.titleToolbar = new Ext.Toolbar({
                            autoHeight: true,
                            items : [
                                {
                                    xtype: 'spacer',
                                    cls: 'toolbar-icon'
                                },
                                i18n.theme + ' :',
                                me.titleEditor = new Ext.Toolbar.TextItem({
                                    cls: 'chapter-title-editor',
                                    text: '___'
                                }),
								'->',
								//'-',
								{
									text: '...',
									xtype: 'tbtext',
									ref: 'keywordsSyummary',
									hidden: true,
									//cls: 'icon-words-gray',
									cls: 'direction-arrow',
									style: 'color: #0000C0; background-repeat: no-repeat; padding-left: 20px;'
								}
                            ]
                        })
                    ]
                }),
				cm: new Ext.grid.ColumnModel({
					columns: columns
				}),
				bbar: new Bible.NavigationToolbar({
					buttonAlign: 'center',
					store: me.store,
					grid: me
				})
			});

			BibleGridPanel.superclass.initComponent.call(me);

            me.addEvents(
                /**
                 * @event refclick
                 * Fires on reference click.
                 * @param {Number} id ID of verse reference
                 */
                "refclick"
            );
			
			me.store.on({
                load : function(s){
                    console.debug('store.load', s.reader.arrayData);
                    var arrayData = s.reader.arrayData,
                        theme = arrayData ? arrayData.theme : '____';
                    me.titleEditor.setText(theme);
                }
            });
		},

		initEvents: function(){
			var me = this,
                view = me.getView(),
                store = me.store,
                booksCombo = me.booksCombo,
                arr = [],
                titleEditor = me.titleEditor,
				record = me.booksStore.getById(me.defaultBook);
            BibleGridPanel.superclass.initEvents.apply(me, arguments);

            me.keyMap.stopEvent = false;

			for(var i=1; i<=record.get('chapters'); i++){
				arr.push([i]);
			}
			me.chaptersStore.loadData(arr);

            // remove removeListener mousewheel to continue editing
            var el = me.getGridEl(),
                e = Ext.EventManager.getListeners(el, 'mousewheel');
            if(e && e[0]){
                Ext.EventManager.removeListener(el, 'mousewheel', e[0][0]);
            }

            me.on({
                scope: me,
                cellclick: function(grid, row, column, e){
                    if (column == 1){
                        var target = e.getTarget('span.ref');
                        if(target){
                            var record = store.getAt(row),
                                ref = record.get('ref'),
                                text = target.innerHTML,
                                id = ref.split('">'+text)[0].split('#');
                            id = id[id.length-1];
                            console.debug(id, ' - ', text);
                            me.fireEvent('refclick', id, text);
                        }
                    }
                },
                cellcontextmenu: function(thisGrid, rowIndex, cellIndex, e) {
                    e.stopEvent();
                    me.selModel.selectRow(rowIndex);
                    me.verseMenu.showAt(e.getXY());
                },
                afteredit: function(e){
                    Bible.updateDBObj('edit', e, CHAPTERS_URL, function(){
                        Bible.EventManager.fireEvent('versechange', me, e.record.get('id'), e.field, e.value);
                    });
                }
//                ,
//                mouseup: function(e){
//                    var s = window.getSelection();
//                    if(s.toString().length > 1){
//                        console.debug('window.getSelection:', s.toString());
//                        this.verseMenu.showAt(e.getXY());
//                    }
//                }
            });

            me.view.on({
				scope: me,
                beforerefresh: function(){
					console.debug('beforerefresh');
                    me.keywordsMatches = [];
                },
                refresh: me.onRefresh
            });

            me.getSelectionModel().on({
                scope: me,
                rowselect: function(sm, index, r){
                    me.verseButton.enable();
                    me.verseMenu.enable();
                    me.verseMenu.keyVerse.setChecked(r.get('keyverse'), true);
                },
                clearselections: function(){
                    me.verseButton.disable();
                }
            });

            me.commentEditor.on('show', function() {
                var h = me.getView().getCell(store.indexOf(me.getSelectionModel().getSelected()), 2).clientHeight;
                this.setSize(this.getWidth() + 3, h + 2);
            });

            var titleTextFieldEditor = new Ext.Editor(Ext.apply({
				alignment: 'l-l',
                autoSize: "width",
                listeners: {
                    complete: function(ed, value, oldValue){
                        me.doLayout(); // fix height if toolbar has changed size
                        if(Bible.isLogged()){
                            var lastParams = me.lastParams;
                            Ext.Ajax.request({
                                url: BOOKS_URL,
                                params: Ext.apply({
                                    action: 'edit',
                                    theme: value
                                }, lastParams),
                                success: function(){
                                    Bible.EventManager.fireEvent('themechange', me, lastParams.book, lastParams.chapter, value);
                                }
                            });
                        } else {
                            Bible.notifyNotLogged();
                        }
                    }
                },
                field: {
                    allowBlank: false,
                    xtype: 'textfield',
                    cls: 'bold theme-editor',
                    boxMinWidth: 150,
                    maxLength: 255,
                    selectOnFocus: true
                }
            }, {
                shadow: false,
                completeOnEnter: true,
                cancelOnEsc: true,
                updateEl: true,
                ignoreNoChange: true
            }));
            titleEditor.el.on('click', function(e, t){
                titleTextFieldEditor.startEdit(t);
            });

            if(me.autoLoadChapter){
                me.loadData({
                    book: me.defaultBook,
                    chapter: me.defaultChapter
                }, me.defaultVerse);
            }

			// =====

			booksCombo.on({
//				scope: me,
				select: function(combo, record, index){
					me.booksComboChange(record);
				},
				change: function(combo, newValue, oldValue){
                    console.debug('booksCombo.on.change:', newValue, '->', oldValue);
					var record = combo.findRecord(combo.valueField, newValue);
					if(record){
                        console.debug('record change', record.get('id'), record.get('name'));
                        me.booksComboChange(record);
                    } else {
                        console.debug('booksCombo change, no record selected. oldValue=', oldValue);
                        combo.setValue(oldValue);
                    }
				}
			});

			me.chaptersCombo.on({
//				scope: me,
				select: function(combo, record, index){
					me.loadData({
						book: booksCombo.getValue(),
						chapter: record.get('id')
					});
				},
				change: function(combo, newValue, oldValue){
					var record = combo.findRecord(combo.valueField, newValue);
					if(record){
                        me.loadData({
                            book: booksCombo.getValue(),
                            chapter: record.get('id')
                        });
                    } else {
                        //console.debug('chaptersCombo change, no record selected. oldValue=', oldValue);
                        combo.setValue(oldValue);
                    }
				}
			});

            me.mon(Bible.data.KeywordsStore, {
                scope: me,
                add:    me.keywordsStoreChanged,
                remove: me.keywordsStoreChanged,
                update: me.keywordsStoreChanged
            });

            me.mon(Bible.EventManager, {
//                scope: me,
                versechange: function(grid, id, property, value){
                    if(me != grid){
                        var record = store.getById(id);
                        if(record){
                            record.set(property, value);
                            record.commit();
                        }
                    }
                },
                themechange: function(grid, book, chapter, newTheme){
                    console.info('themechange', book, chapter, newTheme);
                    if(me != grid && me.isEqual({book: book, chapter: chapter})){
                        titleEditor.setText(newTheme);
                    }
                }
            });

            new Ext.ToolTip({
                target: me.titleEditor.el,
                html: i18n.clickToEdit,
                anchor: 'br-tr',
                renderTo: document.body
            });
            me.clickToEditTip = new Ext.ToolTip({
                target: me.getView().mainBody,
                delegate: 'td.x-grid3-td-comments',
                html: i18n.clickToEdit,
                anchor: 'br-tr',
				renderTo: document.body
            });

            me.commentImgTip = new Ext.ToolTip({
                target: view.mainBody,
                delegate: 'td.comment-knotes',
                trackMouse: true,
                anchor: 'br-tr',
                renderTo: document.body,
                listeners: {
                    beforeshow: function(tip) {
                        var rowIndex = view.findRowIndex(tip.triggerElement),
                            comment = store.getAt(rowIndex).get('comment');
                        comment = Bible.rendererComments(comment);
                        tip.body.dom.innerHTML = comment;
                    }
                }
            });
		},

		// private
		onRefresh: function(){
			var me = this,
				keys = {},
				words = [],
				moreMatches = true,
				summary = [],
				keywordsSyummary = me.titleToolbar.keywordsSyummary;
			console.debug('onrefresh');
			Ext.each(me.keywordsMatches, function(e){
				var id = e.term.id;
				if(!keys[id]){// create if doesn't exist
					keys[id] = 0;
				}
				keys[id]++;
			});
			//console.debug('keys', keys);

			Ext.iterate(keys, function(id, total){
				var key,
					record = Bible.data.KeywordsStore.getById(id);
				if(record){
					key = record.get('keywords');
					key = key.split(',')[0];
					words.push({
						id: id,
						key: key,
						total: total
					});
				}
			});
			words.sort(function (a, b) {
				return b.total - a.total;
			});

			//console.info('keywords summary words');
			//console.dir(words);
			Ext.each(words, function(e){
				var space = '';
				if(moreMatches && e.total == 1){
					space = '<br>';
					moreMatches = false;
				}
				summary.push(space + e.key + '&nbsp;(' + e.total + ')');
			});
			keywordsSyummary.setVisible(summary[0] ? true : false);
			var text = (summary[0] || '') + (summary[1] ? (', ' + summary[1]) : '') + '...';
			text = text.replace('<br>', '');
			keywordsSyummary.setText(text);
			keywordsSyummary.el.dom.qtip = '<b>Sumar ' + i18n.keywords + ':</b><br/>' + summary.join('; ');
			
			if(me.store.isBeforeFilter !== true){
				me.focusLastVerse();
			}
		},
		
		// re focus last verse
		focusLastVerse: function(){
			var me = this,
				record = me.getSelectionModel().getSelected();
			if(record){
				me.selectVerse(record.get('vnumber'));
			}
		},
		
        keywordsStoreChanged: function(){
            if(this.store.showKeywords){
                console.debug('keywords store update');
                this.view.refresh();
            }
        },

		booksComboChange: function(record){
			console.debug('booksComboChange', record.data);
            var me = this,
                p = me.store.lastOptions.params,
				lastChapter = record.get('lastLoaded'),
				chapter = lastChapter ? lastChapter : 1,
				verse,
				params = me.booksCombo.bookExtraParams;
			if(params){
				chapter = params.chapter;
				verse = params.verse;
				console.info('advanced set chapter from book combo', params);
			}
			if(p && (p.book != record.get('id') || p.chapter != chapter)) {
                me.resetNumberOfVerses(record);

				me.chaptersCombo.setValue(chapter);

                me.loadData({
					book: record.get('id'),
					chapter: chapter
				}, verse);
			} else {
				if(verse){
					me.selectVerse(verse);
				}
			}
		},

        /**
         * @param {Ext.data.Record} record Record-book
         */
        resetNumberOfVerses: function(record, book){
            console.debug('resetNumberOfVerses');
            var me = this,
                i = 1,
                a = [],
                lastOptions = me.store.lastOptions;
            if(!record){
                record = me.booksStore.getById(book);
            } else {
                book = record.get('id');
            }
            if(!lastOptions || book != lastOptions.params.book){
                console.debug('book changed to:', book);
                for(; i<=record.get('chapters'); i++){
                    a.push([i]);
                }
                me.chaptersStore.loadData(a);
            }
        },

        /**
         *
         * @param {Object} params
         * @return {Boolean}
         */
        isEqual: function(params){
            // TODO use me.lastParams
            var lastOptions = this.store.lastOptions;
            return ((lastOptions) && Bible.deepEquals(params, lastOptions.params, ['action', 'titles', 'references']));
        },

		/**
		 * @param {Object} params
         * @param {Number} verse - verse to select
		 */
		loadData: function(params, verse){
			//console.debug('loadData', Ext.encode(params));
//			Ext.applyIf(params, {
//				book: this.defaultBook,
//				chapter: this.defaultChapter
//			});
            var me = this,
                record,
                action;

			if(!me.isEqual(params)){

                if(verse){
                    me.selectVerseAfterLoad(verse);
                }
				record = me.booksStore.getById(params.book);
                me.lastParams = Bible.deepCloneObject(params);
				// fix params
				if(record && record.get('chapters') < params.chapter){
					params.chapter = record.get('chapters');
					me.setPage(params, verse);
					return;
				}
				me.store.load({
					params: params
				});

                if(me.hashBook){
                    action = params.book + separator + params.chapter;
                    if(me.defaultVerse){
                        action += separator + me.defaultVerse;
                        // TODO for the moment don't have verse in all actions (like click on verse)
                        delete me.defaultVerse;
                    }
                    Bible.setActions(me.hashBook, action);
                }

				// remember last viewed chapter for every Book
				if(record){
					record.set('lastLoaded', params.chapter);
				}
                me.fireEvent('pagechange', me, params);
				//console.debug('lastOptions: ', Ext.encode(this.store.lastOptions));
			}
		},

        /**
         * @param {Object} params {book: 1, chapter: 2}
         * @param {Number} verse - verse to select
         */
        setPage: function(params, verse){
            console.debug('setPage', params, verse);
            var me = this;
            me.booksCombo.setValue(params.book);

            me.resetNumberOfVerses(null, params.book);

            me.chaptersCombo.setValue(params.chapter);
            me.loadData(params, verse);
        },

        getVerseDetails: function(id, text){
            console.debug('getVerseDetails', id, text);
            Ext.Ajax.request({
                url: VERSE_URL,
                method: 'GET',
                disableCaching: false,
                params: {
                    action: 'get_details',
                    id: id
                },
                scope: this,
                success: function(response){
                    var params = Ext.decode(response.responseText),
                        verse = params.verse;
                    delete params.verse;
                    console.debug('getVerseDetails', params);
                    if(!this.isEqual(params)){
                        this.setPage(params, verse);
                    } else {
                        this.selectVerse(verse);
                    }
                }
            });
        },

        /**
         *
         */
        copyText: function(){
            console.warn('TODO copyText');
            var verse,
                record = this.selModel.getSelected();
            if(record){
                verse = this.booksCombo.getRawValue() + ' ' + record.get('cnumber')+':'+ record.get('vnumber');
                verse += ' ' + record.get('text');
                console.debug('Copy:', verse);
                Bible.copyToClipboard(verse);
            }
        },

        toggleTitles : function(button, pressed){
            this.store.setBaseParam('titles', pressed);
            this.view.refresh();
        },

        toggleKeywords: function(button, show){
            this.store.showKeywords = show;
            console.time('toggleKeywords');
            this.view.refresh();
            console.timeEnd('toggleKeywords');
        },

        toggleBackgroundColors: function(button, pressed){
            this.store.showBackgroundColors = pressed;
            this.view.refresh();
        },

        toggleReferences : function(button, pressed){
            var me = this,
                store = me.store;
            store.setBaseParam('references', pressed);
            Ext.apply(store.lastOptions.params, {
                references: pressed
            });
            if(pressed){
                //console.debug('toggleReferences reload');
                store.reload();
            } else {
                //console.debug('toggleReferences refresh');
                me.view.refresh();
            }
        },

        /**
         * @param {Number} verse
         */
        selectVerseAfterLoad: function(verse){
            this.store.on('load', function(){
                console.debug('store load: selectRow & focusRow');
                this.selectVerse(verse);
            }, this, {single: true});
        },

        /**
         * @param {Number} verse
         */
        selectVerse: function(verse){
            console.info('selectVerse', verse);
            var me = this;
            if(!me.rendered){
                me.on({
                    single: true,
                    afterrender: function(){
                        console.debug('afterrender -> selectVerse', verse);
                        me.selectVerse.defer(200, me, [verse]);
                    }
                });
                return;
            }
            me.getSelectionModel().selectRow(verse-1);
            (function(){
                me.view.focusRow(verse-1);
            }).defer(10, me);
        },

        //private
        setSelectedRecordValue: function(name, value){
            var record = this.getSelectionModel().getSelected();
            if(record){
                var e = {
                    record: record,
                    field: name,
                    value: value
                };
                record.set(name, value);
                Bible.updateDBObj('edit', e, CHAPTERS_URL, function(){
                    Bible.EventManager.fireEvent('versechange', this, record.get('id'), name, value);
                }, this);
            }
        },

        //private
        setBackgroundColor: function(color){
            this.setSelectedRecordValue('bgcolor', color);
        },

        //private
        setKeyVerse: function(checked){
            this.setSelectedRecordValue('keyverse', checked ? '1' : '');
        },

        // private
        getTopToolbarItems: function(){
            var me = this;
            me.booksCombo = new Bible.form.BibleBooksComboBox({
				width: 135,
				listWidth: 150,
                value: me.defaultBook
            });
            me.booksStore = me.booksCombo.store;
            return [
                {
					xtype: 'spacer',
					cls: 'toolbar-icon'
				},
                me.booksCombo,
                me.chaptersCombo = new Ext.form.ComboBox({
                    width: 45,
                    listWidth: 45,
                    displayField:'id',
                    valueField: 'id',
                    value: this.defaultChapter,
                    mode: 'local',
                    allowBlank: false,
                    selectOnFocus: true,
                    lastQuery: '',
                    lazyInit: false,
                    lazyRender: false,
                    forceSelection: true,
                    typeAhead: true,
                    triggerAction: 'all',
                    editable: true,
                    listClass: 'x-combo-list-small',
                    store: me.chaptersStore
                })
                //'->',
                //me.searchField,
				//me.checkFilter
            ];
        },

        getSecondTopToolbarItems: function(){
            var me = this,
                store = me.store,
                baseStateId = 'BibleGridPanel' + (me.hashBook || '') + '-';
            me.verseMenu = new Ext.menu.Menu({
                items: [
                    {
                        text: i18n.backgroundColor,
                        iconCls: 'color-swatch',
						hideOnClick: false,
                        menu: [
                            new Ext.ColorPalette({
                                style: "height: 72px",
                                colors : [
                                    //'000000', '993300', '333300', '003300', '003366', '000080', '333399', '333333',
                                    '800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080',
                                    'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '969696',
                                    'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0',
                                    'FF99CC', 'FFCC99', 'FFFF99', 'CCFFCC', 'CCFFFF', '99CCFF', 'CC99FF', 'FFFFFF'
                                ],
                                scope: me,
                                handler: function(palette, color) {
                                    console.debug('color:', color);
                                    me.setBackgroundColor(color);
                                    me.verseMenu.hide();
                                }
                            }),
                            '-',
                            {
                                text: 'Transparent', // TODO i18n
                                iconCls: 'icon-transparent',
                                scope: me,
                                handler: function(){
                                    me.setBackgroundColor('');
                                }
                            }
                        ]
                    }, {
                        text: 'Verset Cheie', // TODO i18n
                        ref: 'keyVerse',
                        checked: true,
                        scope: me,
                        checkHandler: function(item, checked){
                            console.debug('keyVerse', checked);
                            me.setKeyVerse(checked);
                        }
                    }
                ]
            });

            if(Ext.isIE){
                me.verseMenu.add('-', {
                    text: i18n.copyText,
                    icon: 'images/copy.png',
                    scope: me,
                    handler: me.copyText
                });
            }

            return [
                '-',
                {
                    tooltip: i18n.titles,
                    iconCls: 'chapter-titles',
                    enableToggle: true,
                    pressed: Bible.defaults.titles,
                    stateful: true,
                    stateId: baseStateId + 'titles',
                    stateEvents: ['toggle'],
                    getState : function(){
                        return Ext.apply(Ext.Button.prototype.getState.call(this) || {}, {pressed: this.pressed});
                    },
                    listeners: {
                        scope: me,
                        staterestore: function(button, state){
                            console.debug(button.stateId, 'pressed:', button.pressed);
                            store.setBaseParam('titles', button.pressed);
                        }
                    },
                    scope: me,
                    toggleHandler: me.toggleTitles
                },
                me.referencesButton = new Ext.Button({
                    tooltip: i18n.references + ' (Shift + R)',
                    iconCls: 'chapter-references',
                    enableToggle: true,
                    pressed: Bible.defaults.references,
                    stateful: true,
                    stateId: baseStateId + 'references',
                    stateEvents: ['toggle'],
                    getState : function(){
                        return Ext.apply(Ext.Button.prototype.getState.call(this) || {}, {pressed: this.pressed});
                    },
                    listeners: {
                        scope: me,
                        staterestore: function(button, state){
                            console.debug(button.stateId, 'pressed:', button.pressed);
                            store.setBaseParam('references', button.pressed);
                        }
                    },
                    scope: me,
                    toggleHandler: me.toggleReferences
                }),
                '-',
				/*
                me.userTitleButton = new Ext.Button({
                    tooltip: i18n.chapterTheme,
                    pressed: true,
                    enableToggle: true,
                    iconCls: 'title-chapter-edit',
                    toggleHandler: function(button, pressed){
                        me.titleToolbar.setVisible(pressed);
                        me.doLayout();
                    }
                }),
				*/
                me.commentsButton = new Ext.Button({
                    tooltip: i18n.showHideComments + ' (Shift + C)',
                    enableToggle: true,
                    iconCls: 'icon-notes',
                    stateful: true,
                    stateId: baseStateId + 'comments',
                    stateEvents: ['toggle'],
                    getState : function(){
                        return Ext.apply(Ext.Button.prototype.getState.call(this) || {}, {pressed: this.pressed});
                    },
                    scope: me,
                    toggleHandler: function(button, pressed){
                        me.getColumnModel().setHidden(2, !pressed);
                        me.getColumnModel().setHidden(3, pressed);
						me.focusLastVerse();
                    }
                }),
                //'-',
                me.keywordsButton = new Ext.Button({
                    tooltip: i18n.keywords + ' (Shift + K)',
                    iconCls: 'icon-words',
                    enableToggle: true,
                    pressed: false,
                    stateful: true,
                    stateId: baseStateId + 'keywords',
                    stateEvents: ['toggle'],
                    getState : function(){
                        return Ext.apply(Ext.Button.prototype.getState.call(this) || {}, {pressed: this.pressed});
                    },
                    listeners: {
                        scope: me,
                        staterestore: function(button, state){
                            console.debug(button.stateId, 'pressed:', button.pressed);
                            store.showKeywords = button.pressed;
                        }
                    },
                    scope: me,
                    toggleHandler: me.toggleKeywords
                }),
                {
                    tooltip: 'Activează/Dezactivează ' + i18n.backgroundColor,
                    iconCls: 'color-swatch',
                    enableToggle: true,
                    pressed: true,
                    stateful: true,
                    stateId: baseStateId + 'bgcolors',
                    stateEvents: ['toggle'],
                    getState : function(){
                        return Ext.apply(Ext.Button.prototype.getState.call(this) || {}, {pressed: this.pressed});
                    },
                    listeners: {
                        scope: me,
                        staterestore: function(button, state){
                            console.debug(button.stateId, 'pressed:', button.pressed);
                            store.showBackgroundColors = button.pressed;
                        }
                    },
                    scope: me,
                    toggleHandler: me.toggleBackgroundColors
                },
                //'-',
                me.verseButton = new Ext.Button({
                    tooltip: i18n.verse,
                    disabled: true,
                    iconCls: 'blist',
                    menu: me.verseMenu
                }),
                //,
//                {
//                    text: 'Capitol',
//                    iconCls: 'icon-book',
//                    menu: new Ext.menu.Menu({
//                        items: [
//                            {
//                                text: 'Sumar',
//                                iconCls: 'icon-book-edit'
//                            }
//                        ]
//                    })
//                }
				'->',
                me.searchField,
				me.checkFilter
            ];
        }
	});
    Bible.BibleGridPanel = BibleGridPanel;

    Ext.reg('biblegridpanel', BibleGridPanel);
})();
